# encoding:utf-8

import argparse
import requests
import os
from flask import Flask, request

'''
人流量统计
'''
def parse_arguments():
    parser = argparse.ArgumentParser(description='body_num.')
    parser.add_argument('--debug', type=bool, default=False, help="the button of debug mode")
    parser.add_argument('--port', type=int, default=8080)
    parser.add_argument('--host', type=str, default='0.0.0.0')
    parser.add_argument('--access_token', type=list, default=['19673750','MQjcmg2bZA1jp7ybXx3PKQIj','7DeR6k8QqF4vCsblPmoSaGtjNi11O5d2'], help='list of access_token,first one is AppID,second is API Key,the end is Secret Key ')
    return parser.parse_args()

app = Flask(__name__)
args = parse_arguments()

@app.route('/init', methods=['POST'])
def init():
    API_Key = args.access_token[1]
    Secret_Key = args.access_token[2]

    # client_id 为获取的AK， client_secret 为获取的SK
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + API_Key + '&client_secret=' + Secret_Key
    response = requests.get(host)
    if response:
        access_token = response.json()['access_token']
        global request_url
        request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_num"
        request_url = request_url + "?access_token=" + access_token
        return ('OK,运行环境及配置成功初始化', 200)
    else:
        return ('未响应,请重试!请检查网络状态或access_token是否过期！', 400)

@app.route('/run', methods=['POST'])
def run():
    print("in body_num demo run.")
    response = {}
    try:
        img = request.json['image']
        params = {"image":img}
        headers = {'content-type': 'application/x-www-form-urlencoded'}
        response = requests.post(request_url, data=params, headers=headers).json()
    except:
        response['code'] = 400
        response['msg'] = '错误的Json数据'
    return response

if __name__ == '__main__':
    port = int(os.getenv('FLASK_PROXY_PORT', args.port))
    app.run(host=args.host, port=port, debug=args.debug)
